import { ref, watch } from 'vue'

const defaultSettings = {
  autoSave: true,
  defaultDirectory: '',
  theme: 'dark'
}

export function useSettings() {
  const settings = ref({ ...defaultSettings })

  // 从 ConfigManager 加载设置
  const loadSettings = async () => {
    try {
      const configResult = await window.electronAPI.config.get()
      if(!configResult.success){
        console.error('加载设置失败')
        return
      }
      const config = configResult.data;
      debugger
      settings.value = {
        autoSave: config.editor?.autoSave ?? defaultSettings.autoSave,
        defaultDirectory: config.file?.defaultDirectory ?? defaultSettings.defaultDirectory,
        theme: config.app?.theme === 'dark' ? 'dark' : 'light'
      }
    } catch (error) {
      console.error('加载设置失败:', error)
    }
  }

  // 保存设置到 ConfigManager
  const saveSettings = async () => {
    try {
      await window.electronAPI.config.update({
        editor: {
          autoSave: settings.value.autoSave
        },
        file: {
          defaultDirectory: settings.value.defaultDirectory
        },
        app: {
          theme: settings.value.theme
        }
      })
    } catch (error) {
      console.error('保存设置失败:', error)
    }
  }

  // 重置设置为默认值
  const resetSettings = async () => {
    try {
      await window.electronAPI.config.reset()
      await loadSettings()
    } catch (error) {
      console.error('重置设置失败:', error)
    }
  }

  // 选择文件夹
  const selectFolder = async () => {
    try {
      const result = await window.electronAPI.selectFolder()
      if (result.success && result.path) {
        settings.value.defaultDirectory = result.path
        await saveSettings()
      }
    } catch (error) {
      console.error('选择文件夹失败:', error)
    }
  }

  // 监听设置变化并自动保存
  watch(settings, async () => {
    await saveSettings()
  }, { deep: true })

  // 初始化加载
  loadSettings()

  return {
    settings,
    loadSettings,
    saveSettings,
    resetSettings,
    selectFolder
  }
}